unit TreeFunc;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  ComCtrls,DB,Dialogs;

  function TreeFindItem(Sender: TTreeView;NodeItem: TTreeNode;Name: String):TTreeNode;
  function TreeAddItem(Sender: TTreeView;ItemList: TStrings;BookMark: TBookMark;Resort: Boolean):TTreeNode;
  function TreeGetItem(Sender: TTreeView;ItemList: TStrings):TTreeNode;
  procedure TreeDeleteItem(Sender: TTreeView;ItemList: TStrings;level: integer);

implementation

function TreeFindItem(Sender: TTreeView;NodeItem: TTreeNode;Name: String):TTreeNode;
begin
  if(NodeItem=Nil) then NodeItem := Sender.Items.GetFirstNode
  else NodeItem := NodeItem.GetFirstChild;
  if(NodeItem<>Nil) and (NodeItem.Text <> Name) then
  repeat
    NodeItem := NodeItem.GetNextSibling;
  until (NodeItem=Nil) or (NodeItem.Text=Name);
  Result := NodeItem;
end;

function TreeAddItem(Sender: TTreeView;ItemList: TStrings;BookMark: TBookMark;Resort: Boolean):TTreeNode;
var
  ThisNode,Node: TTreeNode;
  i:    integer;
begin
  Node := Nil;
  for i := 0 to ItemList.Count-1 do
  begin
    ThisNode := TreeFindItem(Sender,Node,ItemList[i]);
    if(ThisNode<>Nil) then Node := ThisNode
    else begin
      if I<Itemlist.count-1
        then begin
          if I=0 then Node := Sender.items.Add(Node, Itemlist[i])
          else Node := Sender.items.AddChild(Node, Itemlist[i]);
        end
        else begin
          if I=0 then Node := Sender.items.AddObject(Node, Itemlist[i],Bookmark)
          else Node := Sender.items.AddChildObject(Node, Itemlist[i],Bookmark);
        end;
      Node.stateIndex := Node.level + 1;
      if Resort and (Node.parent <> nil) then Node.parent.alphasort;
    end;
  end;
  Result := Node;
end;

function TreeGetItem(Sender: TTreeView;ItemList: TStrings):TTreeNode;
begin
  Result := TreeAddItem(Sender, Itemlist, nil, false);
end;

procedure TreeDeleteItem(Sender: TTreeView;ItemList: TStrings;level: integer);
var
  Node, Parent: TTreeNode;
begin
  Node := TreeGetItem(Sender,ItemList);
  while Node.level>=Level do
    begin
      Parent := Node.parent;
      Node.delete;
      if (Parent=nil)or(Parent.hasChildren) then break;
      Node := Parent;
    end;
end;

end.
